package com.shelpe.services.sinbad.service.rtr;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.shelpe.services.sinbad.dto.EffectMetricDto;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.entity.mongo.CostRtr;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;
import com.shelpe.services.sinbad.repository.mongo.CostRtrRepository;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient.GetRtrCustDto;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient.GetRtrCustResponse;

@Service
public class CostService {
	@Autowired
	private UserClient userClient;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private CostRtrRepository costRtrRepository;

	public EffectMetricDto findCost(long userID, Date queryTime,int time) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "user_not_exist");
		CostRtr balance = new CostRtr();
		balance.from(user, queryTime,time);
		CostRtr existing = this.costRtrRepository.findByUserIDAndDateGreaterThan(userID,queryTime);

		EffectMetricDto dto = null;
		if (existing != null && existing.getMetric() != null) {
			dto = new EffectMetricDto();
			BeanUtils.copyProperties(existing.getMetric(), dto);
		}
		return dto;
	}

	public EffectMetricDto syncCost(long userID,int time) {
		Date today = org.apache.commons.lang3.time.DateUtils.truncate(new Date(), Calendar.DATE);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "user_not_exist");
		GetRtrCustResponse res = this.userClient.findRtrCust(user.getNick(), sdf.format(today));

		EffectMetricDto dto = new EffectMetricDto();
		if (res != null && res.getRes() != null && res.getRes().getResultList() != null
				&& res.getRes().getResultList().getResult() != null) {
			List<GetRtrCustDto> dtos = res.getRes().getResultList().getResult();
			if(dtos != null && dtos.size() > 0){
				dto.from(dtos.get(0));

				CostRtr mongoPo = new CostRtr();
				mongoPo.from(user, new Date(),time);
				mongoPo.setMetric(dto);
				this.costRtrRepository.save(mongoPo);
			}
		} else {
			if (res != null && res.getError() != null) {
				dto.setError(res.getError());
			}
		}

		return dto;
	}
}
